package anroid.vstore.provider;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.LoadedFrom;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageAware;

import DTO.PInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.LevelListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.vstore.activities.MainActivity;
import android.widget.ImageView;

public class Helper {
//	public static String SERVICE_URL = "http://125.212.220.96/";
	public static String SERVICE_URL =  "http://123.30.129.248/";
	
	public class FadeInRoundedBitmapDisplayer extends RoundedBitmapDisplayer {

	    int durationMillis;
	    String noRoundedCornersTag;

	    public FadeInRoundedBitmapDisplayer(int durationMillis, int roundPixels,
	            String noRoundedCornersTag) {
	        super(roundPixels);
	        this.durationMillis = durationMillis;
	        this.noRoundedCornersTag = noRoundedCornersTag;
	    }
	    
//	    @Override
//		public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {
//			imageAware.setImageBitmap(bitmap);
//
//			if ((animateFromNetwork && loadedFrom == LoadedFrom.NETWORK) ||
//					(animateFromDisk && loadedFrom == LoadedFrom.DISC_CACHE) ||
//					(animateFromMemory && loadedFrom == LoadedFrom.MEMORY_CACHE)) {
//				animate(imageAware.getWrappedView(), durationMillis);
//			}
//		}

//
	    @Override
	    public void display(Bitmap bitmap, ImageAware imageView,
	    		 LoadedFrom loadedFrom) {
	    	if(imageView.getWrappedView().getTag() != null && imageView.getWrappedView()
	    			.getTag().equals(noRoundedCornersTag)) 
	    		imageView.setImageBitmap(bitmap);
	    	else
	    		super.display(bitmap, imageView, loadedFrom);
	                	
//	        imageView.setImageBitmap( (imageView.getWrappedView().getTag() != null && imageView.getWrappedView()
//	                .getTag().equals(noRoundedCornersTag)) ? bitmap : super
//	                .display(bitmap, imageView, loadedFrom));

	        animate((ImageView) imageView.getWrappedView(), durationMillis);

//	        return bitmap;
	    }

	    public void animate(ImageView imageView, int durationMillis) {
	        AlphaAnimation fadeImage = new AlphaAnimation(0, 1);
	        fadeImage.setDuration(durationMillis);
	        fadeImage.setInterpolator(new DecelerateInterpolator());
	        imageView.startAnimation(fadeImage);
	    }

	}
	public static void recycle(ImageView ivReUse) {
		if (ivReUse == null) {
			return;
		}
		try {
//			if (ivReUse instanceof NLSpriteView) {
//				((NLSpriteView) ivReUse).stopAnimation();
//			}
			android.graphics.drawable.Drawable drawable = ivReUse.getDrawable();
			Bitmap bm = null;
			if (drawable instanceof LevelListDrawable) {
				bm = ((BitmapDrawable) ((LayerDrawable) drawable).getDrawable(0)).getBitmap();
			} else if (drawable instanceof BitmapDrawable) {
				bm = ((BitmapDrawable) drawable).getBitmap();
			}
			if (bm != null) {
				ivReUse.setImageDrawable(null);
				bm.recycle();
				bm = null;
			}
			ivReUse.setImageBitmap(null);
			ivReUse.setOnClickListener(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static boolean haveNetworkConnection(FragmentActivity activity) {
	    boolean haveConnectedWifi = false;
	    boolean haveConnectedMobile = false;

	    ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	    for (NetworkInfo ni : netInfo) {
	        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
	            if (ni.isConnected())
	                haveConnectedWifi = true;
	        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
	            if (ni.isConnected())
	                haveConnectedMobile = true;
	    }
	    return haveConnectedWifi || haveConnectedMobile;
	}
	public static boolean isPackageInstalled(String packagename, Context context) {
//		Intent intent = new Intent(packagename);
//		PackageManager packageManager = context.getPackageManager();
//		List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
//		return activities.size() > 0;
		
		
	    PackageManager pm = context.getPackageManager();
	    try {
	        pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
	        return true;
	    } catch (NameNotFoundException e) {
	        return false;
	    }
		
//		List<ApplicationInfo> packages;
//        PackageManager pm;
//            pm = context.getPackageManager();     
//            for (PInfo packageInfo : MainActivity.installed) {
//        if(packageInfo.pname.equals(packagename)) return true;
//        }        
//        return false;
	}
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
				.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	} 	
	public static Bitmap decodeFile(String URL){
		//Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		try {
			BitmapFactory.decodeStream((InputStream)new URL(URL.replaceAll(" ", "%20")).getContent(),null,o);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//The new size we want to scale to
		final int REQUIRED_SIZE= MainActivity.width;

		//Find the correct scale value. It should be the power of 2.
		int scale=1;
		while(o.outWidth/scale/2>=REQUIRED_SIZE )
			scale*=2;

		//Decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize=scale;
		try {
			return BitmapFactory.decodeStream((InputStream)new URL(URL.replaceAll(" ", "%20")).getContent(), null, o2);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static ArrayList<PInfo> getPackages(FragmentActivity activity) {
	    ArrayList<PInfo> apps = getInstalledApps(activity,false); /* false = no system packages */
	    final int max = apps.size();
	    for (int i=0; i<max; i++) {
	        apps.get(i).prettyPrint();
	    }
	    return apps;
	}

	public static ArrayList<PInfo> getInstalledApps(FragmentActivity activity,boolean getSysPackages) {
	    ArrayList<PInfo> res = new ArrayList<PInfo>();        
	    List<PackageInfo> packs = activity.getPackageManager().getInstalledPackages(0);
	    for(int i=0;i<packs.size();i++) {
	        PackageInfo p = packs.get(i);
	        if ((!getSysPackages) && (p.versionName == null)) {
	            continue ;
	        }
	        PInfo newInfo = new PInfo();
	        newInfo.appname = p.applicationInfo.loadLabel( activity.getPackageManager()).toString();
	        newInfo.pname = p.packageName;
	        newInfo.versionName = p.versionName;
	        newInfo.versionCode = p.versionCode;
	        newInfo.icon = p.applicationInfo.loadIcon( activity.getPackageManager());
	        res.add(newInfo);
	    }
	    return res; 
	}
}
